package com.ls.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChatServer {


    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    public GroupChatServer() {

        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void listen() {

        try {
            while (true) {
                int select = selector.select();
                if (select > 0) {
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        if (key.isAcceptable()) {
                            SocketChannel socketChannel = listenChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + "  上线了");
                            System.out.println("当前连接人数：" + selector.keys().size());
                        }
                        if (key.isReadable()) {
                            readData(key);
                        }
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待...");
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }


    }

    private void readData(SelectionKey key) {
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            channel.read(byteBuffer);
            String msg = new String(byteBuffer.array());
            System.out.println("from 客户端：" + msg);
            sendMsgToOther(msg, channel);
        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 中断连接");
                key.cancel();
                channel.close();
            } catch (IOException ee) {
                ee.printStackTrace();
            }
        }
    }

    private void sendMsgToOther(String msg, SocketChannel self) throws IOException {
        System.out.println("转发到其他客户端...");
        for (SelectionKey key : selector.keys()) {
            Channel channel0 = key.channel();

            if (channel0 instanceof SocketChannel && channel0 != self) {
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                ((SocketChannel) channel0).write(buffer);
            }
        }
    }


    public static void main(String[] args) {

        GroupChatServer server = new GroupChatServer();
        server.listen();
    }
}
